#!/usr/bin/env bash
# Copyright (c) 2021 maminjie <canpool@163.com>
# SPDX-License-Identifier: MulanPSL-2.0

method_def cloc

__CLOC_PL="${BASH_SOURCE[0]%/*}/cloc.pl"

usage_cloc() {
    module_usage "cloc (cl)" "Cloc to count lines of code"
}

alias_def cloc cl
do_cloc() {
    module_do "cloc" "$@"
}

cloc_usage_help() {
    module_usage_help cloc
}

# cloc_do_help subcmd
cloc_do_help() {
    module_do_help cloc "$1"
}

# __cloc_get_subcmd cmd
#   Get the fullname of cmd
# Returns:
#   "" or fullname
__cloc_get_subcmd() {
    local cmd=""
    case "${1}" in
        "h"|"help")
            cmd="help"
            ;;
        "e"|"exec")
            cmd="exec"
            ;;
        "l"|"lang")
            cmd="lang"
            ;;
        "c"|"code")
            cmd="code"
            ;;
        *)
            ;;
    esac
    echo "$cmd"
}

cloc_usage_exec() {
printf "exec (e): Cloc to count lines of code

usage:
    ${PROG} cl e [options] <file(s)/dir(s)/git hash(es)> | <set 1> <set 2> | <report files>

notes:
    type \'${PROG} cl e --help\' for more.
\n"
}

# cloc_do_exec ...
cloc_do_exec() {
    perl $__CLOC_PL $@
}


cloc_usage_lang() {
printf "lang (l): Count languages of code

usage:
    ${PROG} cl lang DIR
\n"
}

# cloc_do_lang DIR
cloc_do_lang() {
    local dir=$1
    if [ ! -d "$dir" ]; then
        cloc_usage_lang; exit
    fi
    # sed -e ':a;N;$!ba;s/\n/,/g' => replace \n to ,
    cloc_do_exec --csv $dir | sed -r -e '1,/^files,language/d' -e '/^[0-9]+,SUM/,$d' | awk -F ',' '{print $2}'
}

cloc_usage_code() {
printf "code (c): Count amount of code

usage:
    ${PROG} cl c [options] DIR|FILE

options:
    -h      Show this help message and exit
    -s      Count the amount of code in subdirectories of DIR
\n"
}

__cloc_code() {
    local info=$(cloc_do_exec $1 | tail -n2 | head -n1)
    echo "$info" | grep -q "unique"
    if [ $? -ne 0 ]; then
        echo "$info" | awk '{print $NF}'
    else
        echo "0"
    fi
}

cloc_do_code() {
    local ARGS=$(getopt -o "s" -n "code" -- "$@")
    eval set -- "${ARGS}"

    local flag_subdir=0

    while true; do
        case "${1}" in
            -h)
                cloc_usage_code; exit
                ;;
            -s)
                flag_subdir=1; shift
                ;;
            --)
                shift; break
                ;;
        esac
    done
    if [ $# -ne 1 ]; then
        cloc_usage_code; exit
    fi
    if [[ $flag_subdir -eq 0 ]]; then
        __cloc_code $1
    else
        local dir="$1"
        if [[ ! -d "$dir" ]]; then
            echo "$dir is not dir, try -h for more"; exit
        fi
        for i in $(ls $dir | sort -u); do
            echo "$i,$(__cloc_code "$dir/$i")"
        done
    fi
}
